﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;


namespace CCPSIP.Group
{
  /// <summary>取得群組圖片(大頭照)</summary>
  public class icon_get : IHttpHandler
  {
    private string kIconDirLatest = ChrisKit.RootDir + "CCPSIP\\GroupIcon\\Latest"; //ios.ccp
    private string kIconPathDefault = ChrisKit.RootDir + "CCPSIP\\GroupIcon\\Default.jpg"; //ios.ccp


    public void ProcessRequest(HttpContext context) {
      HttpRequest req = context.Request;
      HttpResponse resp = context.Response;
      resp.ContentType = "text/plain";
      resp.ContentEncoding = System.Text.Encoding.UTF8;
      DateTime reqTime = DateTime.Now;

      try {
        //【01】取得POST參數，驗證身分
        //
        string idHeader = req.Form["idHeader"];
        string checkcode = req.Form["checkcode"];
        string ClientGID = req.Form["GroupID"];//Client端的群組ID

        SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
        if (userInfo == null) {
          throw new Exception("Error_01: Cannot identify this device");//無法識別此裝置
        }


        //【02】檢查User是否(曾經)是群組成員
        //
        if (!OracleKitGroup.wasMemberOfGroup(userInfo.SIP_Num, ClientGID)) {
          throw new Exception("Error_02: You cannot access the icon");//無權限存取
        }


        //【03】組合檔案路徑
        //
        int GroupID = OracleKitGroup.getGroupID(ClientGID);
        string iconFileName = string.Format("{0}.jpg", GroupID);
        string iconPath = string.Format(@"{0}\{1}", kIconDirLatest, iconFileName);
        string clientFileName = string.Format("{0}.jpg", ClientGID);

        if (!File.Exists(iconPath)) {
          iconPath = kIconPathDefault;
        }


        //【99】回傳HTTP Header與圖片檔案
        // http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
        //
        FileInfo fInfo = new FileInfo(iconPath);
        resp.ContentType = "image/jpeg";
        resp.AppendHeader("Content-Length", fInfo.Length.ToString());
        resp.AppendHeader("Last-Modified", fInfo.LastWriteTime.ToUniversalTime().ToString("r"));
        resp.AppendHeader("Content-Disposition", ChrisKit.getContentDisposition(clientFileName));
        resp.AppendHeader("Cache-Control", "no-cache");

        resp.WriteFile(iconPath, true);//Small File
      }
      catch (Exception ex) {
        resp.ContentType = "application/xml";
        string resultStr = ChrisKit.Ex2Xml(ex, false);
        int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
        resp.AppendHeader("Content-Length", contentLength.ToString());
        resp.Write(resultStr);
      }
      finally {
        resp.Flush();
        resp.Close();
      }
    }


    public bool IsReusable {
      get {
        return false;
      }
    }

  }
}
